package top.infopub.mgr.mkt.web;


import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.domain.DeciProDomain;
import top.infopub.mgr.mkt.service.DeciProAttService;
import top.infopub.mgr.mkt.service.DeciProService;
import top.infopub.mgr.mkt.service.InquiryProService;
import top.infopub.mgr.mkt.vo.DeciProVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.DeciPro;
import top.infopub.model.mkt.DeciProAtt;
import top.infopub.model.mkt.DeciProCoop;
import top.infopub.model.mkt.DeciProQuote;
import top.infopub.model.mkt.DeciProSub;
import top.infopub.model.mkt.InquiryPro;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.github.pagehelper.Page;


/**
 * 决策管理
 * @author wangw
 * @version 2020年1月10日
 * @see DeciProjectController
 * @since
 */
@Controller
@RequestMapping("/deciPro")
public class DeciProjectController extends GenericFlowController {

    @Autowired
    private DeciProService deciProService;
    
    @Autowired
    private DeciProAttService deciProAttService;
    
    @Autowired
    private InquiryProService inquiryProService;
    
    @Autowired
    private StaffInfoService staffInfoService;
    
    @Autowired
    private CoopInfoService coopInfoService;
    
    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 决策列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "mkt/lay-deciPro-list";
    }
    
    /**
     * 决策列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<DeciProDomain> queryDataByCondition(DeciProVo deciProVo, ParamPage paramPage) {
        Page<DeciProDomain> page = new Page<DeciProDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (deciProVo.getEndDate() != null) {
            deciProVo.setEndDate(DateUtils.addDays(deciProVo.getEndDate(), 1));
        }
        //查询时，投标截止日结束日期增加一天
        if (deciProVo.getBidEndDateEndDate() != null) {
            deciProVo.setBidEndDateEndDate(DateUtils.addDays(deciProVo.getBidEndDateEndDate(), 1));
        }
        page = deciProService.selectPageByDomainWhere(page, deciProVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 决策-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<DeciProDomain> queryMyCheckDataByCondition(DeciProVo deciProVo, ParamPage paramPage) {
        Page<DeciProDomain> page = new Page<DeciProDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (deciProVo.getEndDate() != null) {
            deciProVo.setEndDate(DateUtils.addDays(deciProVo.getEndDate(), 1));
        }
        //查询时，投标截止日结束日期增加一天
        if (deciProVo.getBidEndDateEndDate() != null) {
            deciProVo.setBidEndDateEndDate(DateUtils.addDays(deciProVo.getBidEndDateEndDate(), 1));
        }
        deciProVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = deciProService.selectMyCheckByDomainWhere(page, deciProVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 决策-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可决策的记录
        List<InquiryPro> inquiryPros = inquiryProService.selectUsableInquiryPro();
        request.setAttribute("inquiryPros", inquiryPros);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-deciPro-add";
    }
    
    /**
     * 根据id查询决策详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 决策Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request,String id, String processDealWith){
        Map<String, Object> map = new HashMap<String, Object>();
        DeciProVo deciPro = deciProService.selectById(id);
        map.put("deciPro", deciPro);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, deciPro.getProcessId());
        return new ModelAndView("mkt/lay-deciPro-detail", map);
    }
    
    /**
     * 决策-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request,String id) {
        DeciProVo deciPro = deciProService.selectById(id);
        request.setAttribute("deciPro", deciPro);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-deciPro-copy";
    }
    
    /**
     * 新增决策
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request,DeciProVo deciPro) {
        //判断项目是否已存在
        List<DeciPro> deciPros = deciProService.selectListByProCode(deciPro.getProCode());
        if(CollectionUtils.isNotEmpty(deciPros)){
            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("项目【" + deciPro.getProName()
                + "】已决策~");
        }
        String fromChannel = request.getParameter("fromChannel");//项目渠道
        String linkPower = request.getParameter("linkPower");//居住地址
        if(fromChannel.equals("2")){//居间合作
            if(StringUtils.isEmpty(linkPower)){
                return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("居间方不能为空");
            }
        }
        String[] sgCoopId = request.getParameterValues("sgCoopId");//单位名称
        String[] coopEffect = request.getParameterValues("coopEffect");//单位作用
        
        String[] orderIdx = request.getParameterValues("orderIdx");//子项序号
        String[] subName = request.getParameterValues("subName");//子项名称
        String[] subWorkYears = request.getParameterValues("subWorkYears");//子项-合作周期（年）
        String[] subBuildYears = request.getParameterValues("subBuildYears");//子项-建设周期（年）
        String[] subOmYears = request.getParameterValues("subOmYears");//子项-运营周期（年）
        
        String[] itemOrderIdx = request.getParameterValues("itemOrderIdx");//投标报价序号
        String[] itemNames = request.getParameterValues("itemName");//条目名称
        String[] itemPercents = request.getParameterValues("itemPercent");//所占比例
        
        String[] fileAtt31 = request.getParameterValues("fileAtt31");
        String[] fileAtt32 = request.getParameterValues("fileAtt32");
        String[] fileAtt33 = request.getParameterValues("fileAtt33");
        String[] fileAtt34 = request.getParameterValues("fileAtt34");
        String[] fileAtt35 = request.getParameterValues("fileAtt35");
        String[] fileAtt36 = request.getParameterValues("fileAtt36");
        String[] fileAtt37 = request.getParameterValues("fileAtt37");
        String[] fileAtt38 = request.getParameterValues("fileAtt38");
        String[] fileAtt39 = request.getParameterValues("fileAtt39");
        String[] fileAtt40 = request.getParameterValues("fileAtt40");
        
        if(sgCoopId != null && sgCoopId.length > 0){
            for(int i=0; i< sgCoopId.length; i++){
                String coopId = sgCoopId[i];
                String coopeffect = coopEffect[i];
                if(StringUtils.isNotEmpty(coopId)){
                    if(StringUtils.isEmpty(coopeffect)){
                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位作用未选择");
                    }
                }else{
                    if(StringUtils.isNotEmpty(coopeffect)){
                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位名称未选择");
                    }
                }
            }
        }
        
        if(fileAtt31 == null || fileAtt31.length <1){
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("标前承诺未上传");
        }
        if(fileAtt32 == null || fileAtt32.length <1){
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("居间合同未上传");
        }
        if(fileAtt38 == null || fileAtt38.length <1){
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("PPP合同范本未上传");
        }
        
        List<String[]> fileAtt = new ArrayList<String[]>();
        fileAtt.add(fileAtt31);
        fileAtt.add(fileAtt32);
        fileAtt.add(fileAtt33);
        fileAtt.add(fileAtt34);
        fileAtt.add(fileAtt35);
        fileAtt.add(fileAtt36);
        fileAtt.add(fileAtt37);
        fileAtt.add(fileAtt38);
        fileAtt.add(fileAtt39);
        fileAtt.add(fileAtt40);
        
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        
        /**
         * 决策主表处理
         */
        String id = IdFactory.getUUIDUpper();
        deciPro.setId(id);
        deciPro.setHrStaffApplyId(vo.getHrStaffId());
        deciPro.setHrOrgId(deciPro.getDeciOrgId());
        deciPro.setHrDeptId(deciPro.getDeciDeptId());
        deciPro.setBondEndDate(deciPro.getDeciBondEndDate());
        deciPro.setBondMoney(deciPro.getDeciBondMoney());
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(vo.getHrStaffId());
        deciPro.setStaffName(staffInfo.getStaffName());
        deciPro.setAddBy(vo.getId());
        deciPro.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("mkt_deci_pro_codes");
        deciPro.setCodes(codes);
        // 处理processId
        deciPro.setProcessId(IdFactory.getUUIDUpper());
        deciPro.setProcessStatus("1");//审批中
        deciPro.setUptBy(vo.getId());
        deciPro.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        
        //合作单位处理
        List<DeciProCoop> deciProCoops = new ArrayList<DeciProCoop>();
        if(sgCoopId != null && sgCoopId.length > 0){
            for(int i=0; i<sgCoopId.length; i++){
                String coopId = sgCoopId[i];
                String coopeffect = coopEffect[i];
                if(StringUtils.isEmpty(coopId) && StringUtils.isEmpty(coopeffect)){
                    continue;
                }
                String coopid = IdFactory.getUUIDUpper();//自动生成主键
                DeciProCoop deciProCoop = new DeciProCoop();
                deciProCoop.setId(coopid);
                deciProCoop.setDeciProId(id);
                deciProCoop.setSgCoopId(coopId);
                deciProCoop.setCoopEffect(coopeffect);
                deciProCoop.setAddBy(vo.getId());
                deciProCoop.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                deciProCoops.add(deciProCoop);
            }
        
        }
        
        //子项处理
        List<DeciProSub> deciProSubs = new ArrayList<DeciProSub>();
        for(int i=0; i<orderIdx.length; i++){
            String orderId = orderIdx[i];
            DeciProSub deciProSub = new DeciProSub();
            String subId = IdFactory.getUUIDUpper();//自动生成主键
            deciProSub.setId(subId);
            deciProSub.setDeciProId(id);
            deciProSub.setOrderIdx(Integer.parseInt(orderId));
            deciProSub.setSubName(subName[i]);
            deciProSub.setWorkYears(new BigDecimal(subWorkYears[i]));
            deciProSub.setBuildYears(new BigDecimal(subBuildYears[i]));
            deciProSub.setOmYears(new BigDecimal(subOmYears[i]));
            deciProSub.setAddBy(vo.getId());
            deciProSub.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            deciProSubs.add(deciProSub);
        }
        
        //投标报价处理
        List<DeciProQuote> deciProQuotes = new ArrayList<DeciProQuote>();
        for(int i=0; i<itemNames.length; i++){
            if(StringUtils.isNotEmpty(itemNames[i]) && StringUtils.isNotEmpty(itemPercents[i])){
                String orderId = itemOrderIdx[i];
                DeciProQuote deciProQuote = new DeciProQuote();
                String subId = IdFactory.getUUIDUpper();//自动生成主键
                deciProQuote.setId(subId);
                deciProQuote.setDeciProId(id);
                deciProQuote.setOrderIdx(Integer.parseInt(orderId));
                deciProQuote.setItemName(itemNames[i]);
                deciProQuote.setItemPercent(new BigDecimal(itemPercents[i]));
                deciProQuote.setAddBy(vo.getId());
                deciProQuote.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                deciProQuotes.add(deciProQuote);
            }
        }
        /**
         * 上传的文件记录加入集合
         */
        List<DeciProAtt> fileAtts = new ArrayList<DeciProAtt>();
        
        for(String[] proAtt :fileAtt){
            if(proAtt != null){
                for(String file : proAtt){
                    DeciProAtt deciProAtt = createFileAtt(vo, id, file);
                    fileAtts.add(deciProAtt);
                }
            }
        }
        deciProService.addDeciPro(deciPro, deciProCoops, deciProSubs, deciProQuotes, fileAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "决策 -新增决策：项目名="+deciPro.getProName(), null);
        return RspVo.getSuccessResponse();
    }
    
    private DeciProAtt createFileAtt(AuthorizationVO vo, String deciProId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        DeciProAtt fileAtt = new DeciProAtt();
        if(StringUtils.isNotEmpty(fileAttStr[2])){
            fileAtt.setId(fileAttStr[2]);
        }else{
            fileAtt.setId(IdFactory.getUUIDUpper());
        }
        fileAtt.setTypes(fileAttStr[0]);//附件类型
        fileAtt.setDeciProId(deciProId);//项目id
        String fileName = fileAttStr[1].substring(0,fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }
    
    /**
     * 根据id查询决策记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getDeciProById")
    @ResponseBody
    public Map<String, Object> getDeciProById(String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            DeciProVo deciProVo = deciProService.selectById(id);
            AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
            StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
            deciProVo.setStaffName(staffInfo.getStaffName());
            List<DeciProAtt> deciProAtts = deciProAttService.selectAllProAtts(deciProVo.getProCode());
            deciProVo.setDeciProAtts(deciProAtts);
            map.put("deciProVo", deciProVo);
        }
        catch (Exception e) {
            log.error("查询决策记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }
    
    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if(StringUtils.isEmpty(types)){
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "deciProAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types+"|"+file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
}
